package network.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import network.netty.handler.UdpClientHandler;
import org.springframework.boot.SpringApplication;

/**
 * <p>
 * 基于Netty的Udp客户端
 * </p>
 *
 * @author LovelyBigDuck
 * @date 2021/5/28 21:47
 */
public class UdpNettyClient {
    public static void main(String[] args) {

        // 客户端启动辅助类
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        bootstrap.group(workGroup)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChannelInitializer<NioDatagramChannel>() {

                    @Override
                    protected void initChannel(NioDatagramChannel ch) throws Exception {
                        ch.pipeline().addLast(new UdpClientHandler());
                    }
                });
        try {
            // 监听服务端的消息
            Channel channel = bootstrap.bind("localhost",8081).sync().channel();
            channel.closeFuture().sync().await();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
